using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Windows.Forms;
using Microsoft.WindowsCE.Forms;

namespace LastFMPPC
{
	public partial class FormUserInfo : Form
	{
		private static string userInfoFile = "userinfo.xml";
		private static string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);
		private string userInfoPath = appPath + @"\" + userInfoFile;
		UserInfo userInfo = new UserInfo();
		InputPanel inputpanel = new InputPanel();

		public FormUserInfo()
		{
			InitializeComponent();
			inputpanel.Enabled = true;
			
			try
			{
				// loading user info
				if (File.Exists(userInfoPath))
				{
					XmlSerializer xs = new XmlSerializer(typeof(UserInfo));
					TextReader tr = new StreamReader(userInfoPath);
					userInfo = (UserInfo)xs.Deserialize(tr);
					tr.Close();

					textBox_Username.Text = userInfo.username;
					textBox_Password.Text = userInfo.password;
					checkBox_SaveUserInfo.Checked = true;
				}
				else
				{
					userInfo.username = "";
					userInfo.password = "";
					textBox_Username.Text = userInfo.username;
					textBox_Password.Text = userInfo.password;
					checkBox_SaveUserInfo.Checked = false;
				}
			}
			catch (Exception exp)
			{
				throw new LastException("FormUserInfo.FormUserInfo: " + exp.Message);
			}
		}

		public string UserName
		{
			get { return userInfo.username; }
		}

		public string PasswordMD5
		{
			get { return Helper.CalculateMD5(userInfo.password); }
		}

		private void button_OK_Click(object sender, EventArgs e)
		{
			try
			{
				if (checkBox_SaveUserInfo.Checked)
				{
					userInfo.username = textBox_Username.Text;
					userInfo.password = textBox_Password.Text;

					XmlSerializer xs = new XmlSerializer(typeof(UserInfo));
					TextWriter tw = new StreamWriter(userInfoPath);
					xs.Serialize(tw, userInfo);
					tw.Close();
				}
				else
				{
					if (File.Exists(userInfoPath))
					{
						File.Delete(userInfoPath);
					}
				}
			}
			catch (Exception exp)
			{
				throw new LastException("FormUserInfo.button_OK_Click: " + exp.Message);
			}
			finally
			{
				this.DialogResult = DialogResult.OK;
				this.Close();
			}
		}

		private void button_Cancel_Click(object sender, EventArgs e)
		{
			userInfo.username = "";
			userInfo.password = "";
			this.DialogResult = DialogResult.Cancel;
			this.Close();
		}

		private void FormUserInfo_Closing(object sender, CancelEventArgs e)
		{
			inputpanel.Enabled = false;
		}
	}
}
